package com.easylinkin.linkappapi.alarm.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.alarm.dto.AiRule;
import com.easylinkin.linkappapi.alarm.entity.AiAlarmCount;
import com.easylinkin.linkappapi.alarm.mapper.AiAlarmCountMapper;
import com.easylinkin.linkappapi.alarm.service.AiAlarmCountService;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * ai相机预警统计表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
@Slf4j
public class AiAlarmCountServiceImpl extends ServiceImpl<AiAlarmCountMapper, AiAlarmCount> implements
    AiAlarmCountService {

  @Autowired
  private DeviceMapper deviceMapper;
  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  /**
   * 增加
   * @param aiAlarmCount
   */
  @Override
  public void insert(AiAlarmCount aiAlarmCount) {
    /**
     * 验证重复
     */
//    this.checkExist(aiAlarmCount);
    //设置基本属性
    this.setBase(aiAlarmCount);
    this.save(aiAlarmCount);
  }

  /**
   * 根据id编辑
   * @param aiAlarmCount
   */
  @Override
  public void updateOne(AiAlarmCount aiAlarmCount) {
    /**
     * 验证重复
     */
//    this.checkExist(aiAlarmCount);
    //设置基本属性
    this.setBase(aiAlarmCount);
    this.updateById(aiAlarmCount);
  }

  /**
   * ai相机预警统计
   * @param datapushDTO
   */
  @Override
  public void datapushHandler(DatapushDTO datapushDTO) {
    JSONObject data = datapushDTO.getData();
    //获取设备编号
    String deviceCode = data.getString("HostCode");
    //查询改设备是否属于ai相机
    Device device = deviceMapper.findAiDeviceByCode(deviceCode);
    if (null != device){
      //获取事件类型
      String ruleName = data.getString("RuleName");
      QueryWrapper<AiAlarmCount> queryWrapper = new QueryWrapper<>();
      queryWrapper.eq("tenant_id_",device.getTenantId());
      List<AiAlarmCount> alarmCounts = baseMapper.selectList(queryWrapper);
      if (alarmCounts.size() > 0) {
        AiAlarmCount aiAlarmCount = alarmCounts.get(0);
        List<AiRule> list = JSONUtil.toList(aiAlarmCount.getCoordinate(), AiRule.class);
        AtomicInteger i = new AtomicInteger();
        list.forEach(l->{
          if (ruleName.equals(l.getName())){
            l.setNum(l.getNum()+1);
            i.getAndIncrement();
          }
        });
        //等于0表示list中没有流水中的事件类型
        if (i.get() == 0){
          AiRule aiRule = new AiRule();
          aiRule.setName(ruleName);
          aiRule.setNum(1);
          list.add(aiRule);
        }
        aiAlarmCount.setCoordinate(JSONUtil.toJsonStr(list));
        this.updateOne(aiAlarmCount);
      }else {
        //新增
        AiAlarmCount aiAlarmCount = new AiAlarmCount();
        aiAlarmCount.setTenantId(device.getTenantId());
        List<AiRule> list = new ArrayList<>();
        AiRule aiRule = new AiRule();
        aiRule.setName(ruleName);
        aiRule.setNum(1);
        list.add(aiRule);
        aiAlarmCount.setCoordinate(JSONUtil.toJsonStr(list));
        this.insert(aiAlarmCount);
      }
    }
  }

  @Override
  public Map<String, Object> countNum() {
    Map<String, Object> map = new HashMap<>();
    int sum = 0;
    //根据租户id查询统计
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    QueryWrapper<AiAlarmCount> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("tenant_id_",tenantId);
    List<AiAlarmCount> alarmCounts = baseMapper.selectList(queryWrapper);
    if (alarmCounts.size() > 0){
      AiAlarmCount aiAlarmCount = alarmCounts.get(0);
      List<AiRule> list = JSONUtil.toList(aiAlarmCount.getCoordinate(), AiRule.class);
      List<AiRule> ruleList = list.stream().sorted(Comparator.comparing(AiRule::getNum).reversed())
          .collect(Collectors.toList());
      map.put("data",ruleList);
      sum = list.stream().mapToInt(l->l.getNum()).sum();
    }else {
      map.put("data",new ArrayList<>());
    }
    map.put("sum",sum);
    return map;
  }

  /**
   * 验证重复
   */
  private void checkExist(AiAlarmCount aiAlarmCount) {
    QueryWrapper<AiAlarmCount> queryWrapper = new QueryWrapper<>();
    //todo 设置判断重复条件
    //编辑的时候存在id
    Optional.ofNullable(aiAlarmCount.getId()).ifPresent(id -> queryWrapper.ne("id",aiAlarmCount.getId()));
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("该ai相机预警统计已存在");
    }
  }

  /**
   * 设置基本属性
   * @param aiAlarmCount
   */
  private void setBase(AiAlarmCount aiAlarmCount) {
    aiAlarmCount.setModifyTime(new Date());
    //没有id就是新增,有就是编辑
    if (null == aiAlarmCount.getId()){
      aiAlarmCount.setCreateTime(new Date());
    }
  }
}
